var app = getApp()

let trimAll = function trimAll(ele) {
  return new Promise((resolve, reject) => {
    if (typeof ele === 'string') {
      var str = ele.split(' ').join('');
      resolve(str)
    } else {
      reject(`${typeof ele} is not the expected type, but the string type is expected`)
    }

  })
}

let randomTestPromise = function randomIndex2() {
  return new Promise((resolve, reject) => { //在这里在数据库中查询到相应题库的题目
    var selectLib = app.globalData.selectLib
    wx.cloud.database().collection("shuati").where({
      name: selectLib
    }).get().then(res => {
      //拿到对应科目下的所有题
      var subject = res.data[0].title
      var len = subject.length
      //将列表随机打乱3*len次
      for (var i = 0; i < 3 * len; i++) {
        //得到随机数
        var rnd = parseInt(Math.random() * len, 10);
        //交换选项
        var item = subject[0];
        subject[0] = subject[rnd];
        subject[rnd] = item;
      }
      if (i == 3 * len) {
        wx.setStorageSync(
          'subject', subject
        )
        resolve("subject顺序已打乱")
      }
    })
  })
}

let randomPromise = function randomIndex1(selectLib) {
  return new Promise((resolve, reject) => { //在这里在数据库中查询到相应题库的题目
    wx.cloud.database().collection("shuati").where({
      name: selectLib
    }).get().then(res => {
      //拿到对应科目下的所有题
      var subject = res.data[0].title
      var len = subject.length
      //将列表随机打乱3*len次
      for (var i = 0; i < 3 * len; i++) {
        //得到随机数
        var rnd = parseInt(Math.random() * len, 10);
        //交换选项
        var item = subject[0];
        subject[0] = subject[rnd];
        subject[rnd] = item;
      }
      if (i == 3 * len) {
        wx.setStorageSync(
          'subject', subject
        )
        resolve("subject顺序已打乱")
      }
    })
  })
}

/**
 * 比较2个数组元素是否相等的方法
 */
let compareArr = function compareArray(a, b) {
  return new Promise((resolve, reject) => {
    if (a.length !== b.length) reject("与正确答案不符！")
    else {
      // 比较数组的各个元素
      for (var i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) {
          reject("与正确答案不符！")
        }
      }
      resolve("回答正确");
    }
  })
}

/**
 * 比较选中的选项和答案是否相等
 * 返回错误的答案的索引和错误的数量
 */
let compareAnswer = function compareArray(myAnswers, correctAnswer) {
  return new Promise((resolve, reject) => {
    var wrongNum = 0
    var wrongIndex = []
    for (let i = 0; i < correctAnswer.length; i++) {
      var rightAnswers = correctAnswer[i].split("+").sort()
      //拿到正确答案的数组
      var r = myAnswers[i].filter(function (s) {
        return s && s.trim()
      })
      if (r.length == 0) {
        r.push("R")
      }
      if (r.length != rightAnswers.length) {
        wrongNum++
        wrongIndex.push(i)
      } else {
        for (let n = 0; n < rightAnswers.length; n++) {
          if (rightAnswers[n] != r[n]) {
            wrongNum++
            wrongIndex.push(i)
            break
          }
        }
      }
    }
    //得到错误的数量和错误的索引
    resolve({
      wrongNum: wrongNum,
      wrongIndex: wrongIndex
    })
  })
}

//找出数组中为空的项目
let findUnselect = function findUnselect(e) {
  return new Promise((resolve, reject) => {
    var answerNum = 0
    for (let i = 0; i < e.length; i++) {
      var r = e[i].filter(function (s) {
        return s && s.trim()
      })
      if (r.length > 0) {
        answerNum++
      }
    }
    if (answerNum != e.length) {
      reject("有题目没有全部选中")
    } else {
      resolve("选中了全部题目")
    }
  })
}

//对数组进行去重
let unique = function unique(arr) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(arr)) {
      reject('type error!')
    }
    let resArr = []
    for (let i = 0; i < arr.length; i++) {
      if (resArr.indexOf(arr[i]) === -1) {
        resArr.push(arr[i])
      }
    }
    resolve(resArr)
  })
}


/**
 * 找出错误题目，统计做对了的题目
 * @param {所有的题目包括答案}} subject 
 * @param {选择的答案} myAnswers 
 * @param {正确的答案} correctAnswer 
 */
let score = function resultScore(subject, myAnswers, correctAnswer) {
  return new Promise((resolve, reject) => {
    this.compareAnswer(myAnswers, correctAnswer).then(res => {
      var wrongNum = res.wrongNum
      var wrongIndex = res.wrongIndex
      //这里拿到了错误的题目索引和做错的题数量
      //从所有题目中按照索引拿到错误的题目
      var wrongItems = new Array()
      for (let i = 0; i < res.wrongIndex.length; i++) {
        wrongItems.push(subject[res.wrongIndex[i]])
      }
      //算出正确的题目数量
      var done = subject.length - wrongNum
      var wrongText = "";
      for (let i = 0; i < wrongIndex.length; i++) {
        var r = myAnswers[wrongIndex[i]].filter(function (s) {
          return s && s.trim()
        })
        r = r.sort()
        var mySelect = ""
        for (let d = 0; d < r.length; d++) {
          mySelect += r[d]
          if (d < r.length - 1) {
            mySelect += "+"
          }
        }
        wrongText += "正确答案:" + correctAnswer[wrongIndex[i]] + " 你的选项:" + mySelect + "\n";
        wrongText += subject[wrongIndex[i]].question + "\n"
        wrongText += subject[wrongIndex[i]].item1 + "\n"
        wrongText += subject[wrongIndex[i]].item2 + "\n"
        wrongText += subject[wrongIndex[i]].item3 + "\n"
        wrongText += subject[wrongIndex[i]].item4 + "\n" + "\n"
      }
      app.globalData.total = subject.length
      app.globalData.done = done
      app.globalData.wrongText = wrongText
      app.globalData.wrongItems = wrongItems
      resolve("得分计算完成")
    })
  })

}

/**
 * 找出该数组不在原数组中的索引
 * @param {数组} arr 
 * @param {原数组长度} len 
 */
let compareNoOne = function name(arr, len) {
  return new Promise((resolve, reject) => {
    var notExistArr = new Array()
    for (let i = 0; i < len; i++) {
      if (!arr.includes(i)) {
        notExistArr.push(i)
      }
    }
    resolve(notExistArr)
  })
}

module.exports = {
  randomPromise,
  compareArr,
  findUnselect,
  score,
  compareAnswer,
  randomTestPromise,
  unique,
  compareNoOne,
  trimAll
}